import ByteBuffer from 'bytebuffer'
import * as ws from 'ws'
import Packet from './net/Packet'
import Msg from './pb/Msg'
import RoleLogin from './pb/RoleLogin'
import GoodsItem from './pb/GoodsItem'
import RoleLoginOk from './pb/RoleLoginOk'


const server = new ws.Server({ port: 8889 })

server.on('listening', () => {
    console.log('服务器启动成功\n')
})
server.on('connection', (socket: ws.WebSocket) => {
    console.log('\n客户端连接成功\n')

    handleClient(socket)
})
server.on('close', () => {
    console.log('服务器 close')
})
server.on('error', (err: Error) => {
    console.log(`服务器 error err:${err.message}`)
})


const handleClient = (socket: ws.WebSocket) => {
    socket.on('message', (data: Buffer) => {
        let bb = new ByteBuffer()
        bb.append(data)

        const bodyLen = bb.readUint16(0)
        const bodyBuffer = bb.copy(2, 2 + bodyLen)

        dispatch(socket, bodyBuffer)
    })
    socket.on('close', (_code: number, _reason: Buffer) => {
        console.log('\n客户端连接关闭')
    })
}


const dispatch = (socket: ws.WebSocket, bodyBuffer: ByteBuffer) => {
    const packetId = bodyBuffer.readUint16(0)
    const packetBuffer = bodyBuffer.slice(2)
    const packet = new Packet(packetBuffer)

    console.log(`协议 ID:${packetId}`)

    switch (packetId) {
        case Msg.ROLE_LOGIN:
            const roleLogin = RoleLogin.decode(packet)
            console.log('请求登录:', JSON.stringify(roleLogin))

            const goodsItem1 = new GoodsItem(100, 11)
            const goodsItem2 = new GoodsItem(200, 22)

            const roleLoginOk = new RoleLoginOk(10086, 'typescript', [goodsItem1, goodsItem2], roleLogin.video)

            socket.send(roleLoginOk.encode().Buffer())

            const goodsItem3 = new GoodsItem(300, 33)

            socket.send(goodsItem3.encode().Buffer())

            break
        default:
            console.log(`未知协议 ID::${packetId}`)
            break
    }
}
